package org.iipg.common.data.component;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.google.common.net.HttpHeaders;
import org.iipg.common.data.dto.UserDto;
import org.iipg.common.data.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/** Author: zhuhy163@163.com Date: 2020/9/3 */
@Component
@Slf4j
public class SysUserHolder {

	public UserDto getCurrentUser(String tokenSecret) {
		try {
			// 从Header中获取用户信息
			ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder
					.getRequestAttributes();
			HttpServletRequest request = servletRequestAttributes.getRequest();
			String authHeaderStr = request.getHeader(HttpHeaders.AUTHORIZATION);
			String[] arr = authHeaderStr.split(" ");
			if (!arr[0].equalsIgnoreCase("Bearer") || arr.length != 2) {
				log.warn("Token type error!");
				return UserDto.defaultUser();
			}

			String token = arr[1];
			log.info("token=" + token);
			if (StrUtil.isEmpty(token)) {
				return UserDto.defaultUser();
			}

			String payloadStr = "";
			try {
				payloadStr = JwtUtil.verifySignature(token, tokenSecret);
			} catch (Exception e) {
				log.error("token签名验证失败");
				return UserDto.defaultUser();
			}

			JSONObject userJsonObject = new JSONObject(payloadStr);
			UserDto userDTO = new UserDto();
			BeanUtil.copyProperties(userJsonObject, userDTO);

			List<Map> authorities = Convert.toList(Map.class, userJsonObject.get("authorities"));
			List<String> names = new ArrayList<>();
			for (Map item : authorities) {
				if (item.containsKey("authority")) {
					names.add((String) item.get("authority"));
				}
			}
			userDTO.setAuthorities(names);
			return userDTO;
		}
		catch (Exception ex) {
			log.warn(ex.getMessage());
		}
		return UserDto.defaultUser();
	}

}
